package io.kiki.sba.registry.server.clientInterface.resource;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.metrics.ReporterUtils;
import io.kiki.sba.registry.server.clientInterface.bootstrap.Bootstrap;
import io.kiki.sba.registry.util.Bool;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;


@Path("health")
public class HealthResource {

    @Autowired
    Bootstrap bootstrap;

    @PostConstruct
    public void init() {
        MetricRegistry metrics = new MetricRegistry();
        metrics.register("healthCheck", (Gauge<Response>) () -> getHealthCheckResult());
        ReporterUtils.startSlf4jReporter(60, metrics);
    }

    @GET
    @Path("check")
    @Produces(MediaType.APPLICATION_JSON)
    public javax.ws.rs.core.Response checkHealth() {
        ResponseBuilder builder = javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.OK);
        Response response = getHealthCheckResult();
        builder.entity(response);
        if (!response.isSuccess()) {
            builder.status(Status.INTERNAL_SERVER_ERROR);
        }

        return builder.build();
    }

    protected StringBuilder getStatus(Bool result) {
        StringBuilder sb = new StringBuilder("SessionServerBoot ");
        boolean start = false;

        start = bootstrap.getMetaStart();
        boolean ret = start;
        sb.append(", MetaServerStart:").append(start);

        start = bootstrap.getSchedulerStart();
        ret = ret && start;
        sb.append(", SchedulerStart:").append(start);

        start = bootstrap.getHttpStart();
        ret = ret && start;
        sb.append(", HttpServerStart:").append(start);

        start = bootstrap.getServerStart();
        ret = ret && start;
        sb.append(", SessionServerStart:").append(start);

        start = bootstrap.getServerForSessionSyncStart();
        ret = ret && start;
        sb.append(", ServerForSessionSyncStart:").append(start);

        start = bootstrap.getDataStart();
        ret = ret && start;
        sb.append(", ConnectDataServer:").append(start);

        start = bootstrap.getConsoleStart();
        ret = ret && start;
        sb.append(", ConsoleServer:").append(start);

        result.setBool(ret);
        return sb;
    }

    private Response getHealthCheckResult() {
        Bool ret = Bool.newFalse();
        String desc = getStatus(ret).toString();

        return ret.isTrue() ? Response.buildSuccessResponse(desc) : Response.buildFailedResponse(desc);
    }
}
